<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('add-employee')" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
          <!-- <el-button size="small" type="primary" :disabled="!checkPermission('add-employee')" @click="showDialog=true">新增员工</el-button> -->
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" :formatter="formatEmployment" sortable="" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">  <el-switch :value="row.enableState ===1 " /></template>

          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <!-- {{Object.keys(scope)}} -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :total="page.total" :page-size="page.size" layout="prev, pager, next" @current-change="currentChange" />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" @addEmployee="getEmployeeList" />
      <AssignRole ref="assignRole" :user-id="userId" :show-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from '@/views/employees/components/add-employee.vue'
import AssignRole from '@/views/employees/components/assign-role.vue'
export default {
  components: {
    AddEmployee,
    AssignRole
  },

  data() {
    return {
      showDialog: false,
      showRoleDialog: false, userId: '',
      list: [],
      page: {
        size: 5,
        page: 1,
        total: 0

      }
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // checkPermission(btnName) {
    //   return this.$store.state.user.userInfo.roles.points.indexOf(btnName) !== -1
    // },
    async assignRole(id) {
    //  这里是弹窗的地方，需要调用弹窗的数据回显函数
      await this.$refs.assignRole.getUserDetailById(id)
      this.userId = id
      this.showRoleDialog = true
    },
    async getEmployeeList() {
      // 定义了要把数据传进来，不然没有效果
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      // 因为本地服务器没有账户状态，所以我们需要自己加
      // 对接口 user 所有员工进行处理，如果没有这个值就补个1
      this.list = rows.map(user => {
        return {
          // 把这个接口展开，加个enableState，如果有值就用，没有就变成1
          ...user,
          enableState: user.enableState || 1
        }
      })
    },
    currentChange(newPage) {
      // ele-ui封装的current-change  我们让当前点击的page页数等于新的就好了，然后重新获取列表
      this.page.page = newPage
      this.getEmployeeList()
    },
    formatEmployment(row, col, cell, index) {
      // 格式化表格内容：就是把一些东西变成另外一些东西  formater是ele-ui封装的，可以格式化表格，
      // 不是放table里面，而是你要哪个格式化就放那里
      // 可以传4个参数，row,col,cell,index，cell是单元格内容，我们要的就是这个
      // 数据太多，我们不好写太多 if 封装好了，我们引入过来用
      const obj = employeesEnum.hireType.find(el => Number(el.id) === Number(cell))
      return obj ? obj.value : '未知'
    },
    async exportExcel() {
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.page.total
      })
      console.log('源数据', rows)
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)// 拿到那堆中文作为头
      const data = rows.map(user => {
        return this.obj2arr(user, dict)
      })
      console.log('转化后', data)
      // 另一种按需导入，不是在上面导入，而是用res接收promise对象，解构里面的json
      // const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header,
        data
      })
    },
    obj2arr(user, dict) {
      const newUser = []
      for (const key in dict) {
        const enKey = dict[key]
        // enKey  是dict里面的值
        // console.log('enkey', enKey)
        const value = user[enKey]
        // value是接口根据enKey这些名字，对应的值
        // console.log('value', value)
        // 转一下格式
        if (enKey === 'formOfEmployment') {
          // 聘用形式的处理
          const obj = employeesEnum.hireType.find(el => el.id === value)
          newUser.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 时间的处理
          newUser.push(formatDate(value))
        } else {
          newUser.push(value)
        }
      }
      return newUser
    },
    async delEmployee(id) {
      // 二次询问
      await this.$confirm('确定删除吗')
      // 发请求
      await delEmployee(id)
      // 提醒用户
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployeeList()
    }
  }
}
</script>

<style>

</style>
